<?php
# тест возобновления разработки
$microtime   = microtime(true);
$curr_time   = date("Y-m-d H:i:s");
$check_url   = "http://efoxxi.110mb.com/postcheck.php";
$vk_url      = "http://vkontakte.ru/index.php";
$timeout     = 20;
$my_ip       = my_ip($check_url, $timeout);
$step        = 100;
$query       = "SELECT proxy, port FROM `proxy`";
$user_agent  = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
$vk          = 0;
$vk_counter  = 0;

echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><pre>\n[".$curr_time."]\n\n";

$dbcnx = @mysql_connect("localhost", "root", "qqq");
mysql_query("SET NAMES utf8");
@mysql_select_db("vknew", $dbcnx);
$id_result = mysql_query($query);
$id_counter = 0;
while($id_row = mysql_fetch_row($id_result)) {
	list($proxy, $port) = $id_row;
	$proxies[$id_counter] = $proxy;
	$ports  [$id_counter] = $port;
	$id_counter++; // количество id вконтакте
}

for($p = 0; $p < count($proxies); $p += $step) { // можно оптимизировать в будующем
	unset($proxy_arr, $port_arr, $good);
	for ($t = 0; (($t < $step) && (($p+$t) < count($proxies))); $t++) {
		$proxy_arr[$t] = $proxies[$p+$t];
		$port_arr [$t] = $ports  [$p+$t];
	}
	$good = check_proxy($proxy_arr, $port_arr, $p, $vk, $my_ip, $check_url, $timeout, $user_agent);
	$count_good_proxies = count($good);
	foreach($good as $t => $value) {
		//echo ($p+$t)."\t".$good[$t]['proxy'].":".$good[$t]['port']."\n";
		$vk_good[$vk_counter]['proxy'] = $good[$t]['proxy'];
		$vk_good[$vk_counter]['port']  = $good[$t]['port'];
		$vk_counter++;
	}
	echo "GOOD=".$count_good_proxies."\n";
}

$vk = 1;
for($p = 0; $p < count($vk_good); $p += $step) {
	unset($proxy_arr, $port_arr, $good);
	for ($t = 0; (($t < $step) && (($p+$t) < count($vk_good))); $t++) {
		$proxy_arr[$t] = $vk_good[$p+$t]['proxy'];
		$port_arr [$t] = $vk_good[$p+$t]['port'];
	}
	$good = check_proxy($proxy_arr, $port_arr, $p, $vk, $my_ip, $vk_url, $timeout, $user_agent);
	$count_good_proxies = count($good);
}
mysql_close($dbcnx);
echo "</pre>\n";

########### FUNCTIONS #############

function eflush() {
	ob_flush();
	flush();
}


function my_ip($check_url, $timeout) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,            $check_url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT,        $timeout);
	curl_setopt($ch, CURLOPT_POST,           1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,     "pr=");
	$result = curl_exec($ch);
	curl_close($ch);
	$str = split("\n", $result);
	if($str[0] == "GOODPROXY") {
		$ip = $str[2];
		return $ip;
	}
}


function check_proxy($proxy_arr, $port_arr, $p, $vk, $my_ip, $url, $timeout, $user_agent) {
	$count_good_proxies = 0;
	$good = array();

	$mh = curl_multi_init();
	for($t = 0; $t < count($proxy_arr); $t++) {
		$ch[$t] = curl_init($url);
		curl_setopt($ch[$t], CURLOPT_URL,            $url);
		curl_setopt($ch[$t], CURLOPT_USERAGENT,      $user_agent);
		curl_setopt($ch[$t], CURLOPT_PROXY,          $proxy_arr[$t].":".$port_arr[$t]);
		curl_setopt($ch[$t], CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch[$t], CURLOPT_TIMEOUT,        $timeout);
		curl_setopt($ch[$t], CURLOPT_POST,           1);
		curl_setopt($ch[$t], CURLOPT_POSTFIELDS,     "pr=".$proxy_arr[$t].":".$port_arr[$t]);
		curl_multi_add_handle ($mh, $ch[$t]);
		#echo $proxy_arr[$t].":".$port_arr[$t]."\n";
	}

	do {
		$n = curl_multi_exec($mh, $active);
		usleep(100000); // чтобы не грузить сразу проц
	} while($active > 0);

	$check_time = date("Y-m-d H:i:s");

	for($t = 0; $t < count($proxy_arr); $t++) {
		$result[$t] = curl_multi_getcontent($ch[$t]);
		$info       = curl_getinfo($ch[$t]);
		$code[$t]   = $info['http_code'];
		$time[$t]   = $info['total_time'];

		curl_multi_remove_handle($mh, $ch[$t]);
		curl_close($ch[$t]);
	}
	curl_multi_close($mh);

	for($t = 0; $t < count($proxy_arr); $t++) {
		if($code[$t] != 0) {
			if ($code[$t] == 200) {
				if(isset($result[$t])) {
					$str = split("\n", $result[$t]);
					if($vk == 0) {
						if($str[0] == "GOODPROXY") {
							$pr = $str[1];
							$ip = $str[2];
							$xf = $str[3]; # HTTP_X_FORWARDED_FOR
							echo ($p+$t)." proxy=".$proxy_arr[$t].":".$port_arr[$t];
							echo " ip=".$ip;
							if($xf != "") { echo " xf=".$xf; }
							echo " time=".$time[$t]."\n";
							$query_ins  = "INSERT INTO `proxy_check` (`proxy`, `port`, `vk`, `ip`";
							$query_ins .= " `code`, `an`, `er`, `time`, `check_time`, `result`)";
							$query_ins .= " VALUES ('".$proxy_arr[$t]."', '".$port_arr[$t]."', '".$vk."', '".$ip."','200',";
							if( ($xf == $my_ip) || (substr($xf, 0, strpos($xf, ",")) == $my_ip) ) {  # не совсем корректная проверка
								$query_ins .= " '0',";
							} else {
								$query_ins .= " '1',";
							}
							$query_ins .= " '0', '".$time[$t]."', '".$check_time."', UNHEX('".bin2hex($result[$t])."'))";
							$good[$t]['proxy'] = $proxy_arr[$t];
							$good[$t]['port']  = $port_arr [$t];
							$count_good_proxies++;
						} else {             ### BAD ANSWER
							$query_ins  = "INSERT INTO `proxy_check` (`proxy`, `port`, `vk`,";
							$query_ins .= " `code`, `er`, `time`, `check_time`, `result`)";
							$query_ins .= " VALUES ('".$proxy_arr[$t]."', '".$port_arr[$t]."', '".$vk."',";
							$query_ins .= " '200', '1', '".$time[$t]."', '".$check_time."', UNHEX('".bin2hex($result[$t])."'))";
						}
					} else {  # if($vk == 0)
						if(count($str) > 200) {
							$query_ins  = "INSERT INTO `proxy_check` (`proxy`, `port`, `vk`,";
							$query_ins .= " `code`, `er`, `time`, `check_time`, `result`)";
							$query_ins .= " VALUES ('".$proxy_arr[$t]."', '".$port_arr[$t]."', '".$vk."',";
							if(substr($str[3], strpos($str[3], "id=") + 4, 9) == "vkontakte") {
								echo ($p+$t)." vkproxy= ".$proxy_arr[$t].":".$port_arr[$t];
								echo " time= ".$time[$t]."\n";
								$query_ins .= " '200', '0', '".$time[$t]."', '".$check_time."', UNHEX('".bin2hex($result[$t])."'))";
								$good[$t]['proxy'] = $proxy_arr[$t];
								$good[$t]['port']  = $port_arr [$t];
								$count_good_proxies++;
							} else {     ### BAD ANSWER
								$query_ins .= " '200', '1', '".$time[$t]."', '".$check_time."', UNHEX('".bin2hex($result[$t])."'))";
							}
						} else {         ### BAD ANSWER
							$query_ins .= " '200', '1', '".$time[$t]."', '".$check_time."', UNHEX('".bin2hex($result[$t])."'))";
							
						}
					}         # if($vk == 0)
				} else {                 ### NO RESULT
					$query_ins  = "INSERT INTO `proxy_check` (`proxy`, `port`, `vk`,";
					$query_ins .= " `code`, `er`, `time`, `check_time`)";
					$query_ins .= " VALUES ('".$proxy_arr[$t]."', '".$port_arr[$t]."', '".$vk."',";
					$query_ins .= " '200', '2', '".$time[$t]."', '".$check_time."')";
				}
			} else {                     ### CODE != 200
				$query_ins  = "INSERT INTO `proxy_check` (`proxy`, `port`, `vk`,";
				$query_ins .= " `code`, `er`, `time`, `check_time`)";
				$query_ins .= " VALUES ('".$proxy_arr[$t]."', '".$port_arr[$t]."', '".$vk."',";
				$query_ins .= " '".$code[$t]."', '3', '".$time[$t]."', '".$check_time."')";
			}
		} else {                         ### TIMEOUT
			$query_ins  = "INSERT INTO `proxy_check` (`proxy`, `port`, `vk`,";
			$query_ins .= " `er`, `time`, `check_time`)";
			$query_ins .= " VALUES ('".$proxy_arr[$t]."', '".$port_arr[$t]."', '".$vk."',";
			$query_ins .= " '4', '".$time[$t]."', '".$check_time."')";
		}
		mysql_query($query_ins);
	}
	return $good;
}

?>
